package com.example.chat.view

import android.content.Context
import android.util.Log
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.Button
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.*
import androidx.core.content.ContextCompat.getSystemService
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.chat.R
import com.example.chat.viewmodel.ChatDetailViewModel
import com.example.chat.viewmodel.MessageType
import com.example.featuresdk.core.AbstractFeatureSDK
import com.example.featuresdk.view.FeatureEntry
import com.example.featuresdk.view.FullScreen
import com.example.featuresdk.view.HeaderBackFeatureEntry
import com.example.featuresdk.viewmodel.NavigationViewModel


@Composable
fun ChatDetailScreen(
    chatKey:String?,
    chatTitle:String?,
    navigationViewModel: NavigationViewModel,
    featureSDK: AbstractFeatureSDK,
    chatVewModel: ChatDetailViewModel = viewModel()){

    FullScreen(navigationViewModel){

        ChatDetailScreenHeader(chatKey,chatTitle,navigationViewModel)

        ChatDetailView(chatKey,chatTitle,navigationViewModel, featureSDK, chatVewModel)

        ChatDetailScreenFooter(navigationViewModel,chatVewModel)
    }
}

@Composable
inline fun ChatDetailScreenHeader(chatKey:String?,
                                  chatTitle:String?,
                                  navigationViewModel: NavigationViewModel){
    Row (modifier = Modifier
        .height(navigationViewModel.appHeaderBarHeightDp.dp)
        .background(Color.LightGray)
        .fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically){

        HeaderBackFeatureEntry(navigationViewModel)

        Text(text = "$chatTitle",modifier = Modifier.width((navigationViewModel.screenWithDp - navigationViewModel.headerIconSizeDp * 2).dp),
            textAlign = TextAlign.Center)

        FeatureEntry(R.drawable.ic_edit, onClick = {
            navigationViewModel.navHostController.navigate("chat/edit"){
                launchSingleTop = true
            }
        })
    }
}

@OptIn(ExperimentalUnitApi::class)
@Composable
inline fun ChatDetailView(
    chatKey:String?,
    chatTitle:String?,
    navigationViewModel: NavigationViewModel,
    featureSDK: AbstractFeatureSDK,
    chatDetailViewModel: ChatDetailViewModel = viewModel()
) {

    LazyColumn (modifier = Modifier
        .background(Color.Transparent)
        .height((
                if (chatDetailViewModel.messageTypeSelectorVisible.value)
                    navigationViewModel.appBodyHeightDp - chatDetailViewModel.messageTypeSelectorHeightDp
                else
                    navigationViewModel.appBodyHeightDp
                ).dp)
        .width(navigationViewModel.screenWithDp.dp)) {

        items(chatDetailViewModel.chatMessages){ message ->

            if(message.sender == "me") {
                Row(modifier = Modifier.height(40.dp),
                    horizontalArrangement = Arrangement.End,
                    verticalAlignment = Alignment.Bottom
                ) {

                    Spacer(modifier = Modifier.width(50.dp))

                    Text(text = "${message.content}",
                        modifier = Modifier.width((navigationViewModel.screenWithDp - 100).dp),
                        color = Color.Green,
                        fontSize = TextUnit(5f, TextUnitType.Em),
                        textAlign = TextAlign.End,
                        overflow = TextOverflow.Visible)

                    Image(painter = painterResource(id = R.drawable.ic_apache),
                        contentDescription = "",
                        modifier = Modifier
                            .width(40.dp)
                            .height(40.dp))
                }
            }else{
                Row(modifier = Modifier.height(40.dp),
                    horizontalArrangement = Arrangement.Start,
                    verticalAlignment = Alignment.Bottom
                ) {

                    Image(painter = painterResource(id = R.drawable.ic_user),
                        contentDescription = "",
                        modifier = Modifier
                            .width(40.dp)
                            .height(40.dp))

                    Text(text = "${message.content}",
                        modifier = Modifier.background(Color.White),
                        color = Color.Black,
                        fontSize = TextUnit(5f, TextUnitType.Em),
                        textAlign = TextAlign.Left)
                }
            }
        }
    }
}

@OptIn(ExperimentalUnitApi::class)
@Composable
inline fun ChatDetailScreenFooter(navigationViewModel: NavigationViewModel, chatVewModel: ChatDetailViewModel) {

    Column() {
        ChatTypeSelector(navigationViewModel, chatVewModel)

        Log.i("","messageType = ${chatVewModel.messageType.value}")
        when(chatVewModel.messageType.value){
            MessageType.Voice -> {
                chatVewModel.messageTypeSelectorVisible.value = false
            }
            MessageType.Text -> {
                //TODO: set focus to text input field to show software keyboard
            }
            MessageType.Emoji -> {
                EmojiDashboard(chatVewModel)
                chatVewModel.messageTypeSelectorVisible.value = true
            }
            MessageType.Photo -> {
                Text(text = "*************Photo************")
                //TODO: shwo photo selector in new screen
            }
            MessageType.None -> {
                chatVewModel.messageTypeSelectorVisible.value = false
            }
            MessageType.Others -> {
                chatVewModel.messageTypeSelectorVisible.value = true
                ChatTypeSelectorMore(navigationViewModel, chatVewModel)
            }
        }
    }
}

@OptIn(ExperimentalUnitApi::class)
@Composable
inline fun ChatTypeSelector(navigationViewModel: NavigationViewModel, chatVewModel: ChatDetailViewModel) {

    Row(modifier = Modifier
        .height(navigationViewModel.appBottomBarHeightDp.dp)
        .background(Color.LightGray)
        .fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {

        if (chatVewModel.messageType.value != MessageType.Voice) {
            FeatureEntry(icon = R.drawable.ic_voice, onClick = {
                chatVewModel.messageType.value = MessageType.Voice
            })
        } else {
            FeatureEntry(icon = R.drawable.ic_keyboard, onClick = {
                chatVewModel.messageType.value = MessageType.Text
            })
        }

        if (chatVewModel.messageType.value == MessageType.Voice) {
            OutlinedButton(modifier = Modifier
                .width(chatVewModel.textMessageFieldWidthDp.value.dp)
                .height(30.dp)
                .border(Dp.Hairline, Color.LightGray),
                onClick = {
                    //TODO: launch the voice record
                }) {
                Text(text = "Click and Say")
            }
        } else {

            BasicTextField(value = chatVewModel.chatContent.value,
                onValueChange = {
                    chatVewModel.chatContent.value = it
                },
                modifier = Modifier
                    .width(chatVewModel.textMessageFieldWidthDp.value.dp)
                    .height(30.dp)
                    .border(Dp.Hairline, Color.LightGray)
                    .onFocusChanged {
                        if(it.isFocused){
                            chatVewModel.messageTypeSelectorVisible.value = true
                            chatVewModel.messageType.value = MessageType.Text
                        }else{
                            chatVewModel.messageTypeSelectorVisible.value = false
                        }
//                        Log.i("","BasicTextField it.hasFocus=${it.hasFocus} it.isCaptured=${it.isCaptured} it.isFocused=${it.isFocused}")
                    }
                    .background(Color.White),
                keyboardOptions = KeyboardOptions(
                    keyboardType = KeyboardType.Text,
                    imeAction = ImeAction.Send
                ),
                keyboardActions = KeyboardActions(
                    onSend = {
                        chatVewModel.sendMessage()
                    }
                ),
                singleLine = true
            )
        }

        if (chatVewModel.messageType.value != MessageType.Emoji) {
            FeatureEntry(icon = R.drawable.ic_emoji, onClick = {
                chatVewModel.messageType.value = MessageType.Emoji
            })
        }

        if (chatVewModel.messageType.value == MessageType.Emoji) {
            FeatureEntry(icon = R.drawable.ic_keyboard, onClick = {
                chatVewModel.messageType.value = MessageType.Text
            })
        }

        if(chatVewModel.chatContent.value.isBlank()) {
            FeatureEntry(icon = R.drawable.ic_add, onClick = {
                chatVewModel.messageType.value = MessageType.Others
            })

            chatVewModel.textMessageFieldWidthDp.value = navigationViewModel.screenWithDp - 34 * 3

        }else{
            chatVewModel.textMessageFieldWidthDp.value = navigationViewModel.screenWithDp - 34 * 4

            Button(onClick = {
                chatVewModel.sendMessage()
            }, modifier = Modifier
                .height(30.dp)
                .background(Color.Cyan)
                .padding(0.dp)){
                Text("Send",fontSize = TextUnit(3f, TextUnitType.Em), textAlign = TextAlign.Center)
            }
        }
    }
}

@Composable
inline fun ChatTypeSelectorMore(navigationViewModel: NavigationViewModel, chatVewModel: ChatDetailViewModel) {

    LazyRow(){
        items (10) {
            ChatTypeSelectorEntry(icon = R.drawable.ic_cassandra, "Cascadra",onEntrySelected = {})
        }
    }
}

@OptIn(ExperimentalUnitApi::class)
@Composable
inline fun ChatTypeSelectorEntry(icon: Int, label: String, crossinline onEntrySelected:()->Unit) {
    Column (modifier = Modifier
        .background(Color.Transparent)
        .clickable { onEntrySelected() },
        verticalArrangement = Arrangement.Center,
        horizontalAlignment = Alignment.CenterHorizontally){

        Image(painter = painterResource(icon),
            contentDescription = "",
            modifier = Modifier
                .width(50.dp)
                .height(50.dp)
        )

        Text(text = label,
            color = Color.Black,
            fontSize = TextUnit(5f, TextUnitType.Em),
            fontStyle = FontStyle.Normal,
            fontWeight = FontWeight.Normal
        )
    }
}

@Composable
fun EmojiDashboard(chatVewModel: ChatDetailViewModel){

    val emojiIcons = remember {
        chatVewModel.emojiIcons
    }

    //list of emoji categories
    LazyRow(modifier = Modifier
        .padding(2.dp)
        .background(Color.LightGray)){
        items(emojiIcons.values.toList()){ it ->
            Image(painter = painterResource(it),
                contentDescription = "",
                modifier = Modifier
                    .width(30.dp)
                    .height(30.dp)
                    .padding(2.dp)
            )
        }
    }

    LazyRow(modifier = Modifier.padding(4.dp).background(Color.Gray)){

        item(){
            DefaultEmojis(400,chatVewModel.messageTypeSelectorHeightDp, Color.Magenta)
        }

        item(){
            FavoriteEmojis(400,chatVewModel.messageTypeSelectorHeightDp, Color.White)
        }
   }
}


@Composable
inline fun DefaultEmojis(width:Int, height:Int, backgroundColor: Color){
    Box(modifier = Modifier.width(width.dp).height(height.dp).background(backgroundColor)){
        LazyColumn {
            items (8) {

                Image(painter = painterResource(R.drawable.ic_cassandra),
                    contentDescription = "",
                    modifier = Modifier
                        .width(400.dp)
                        .height(50.dp)
                        .padding(2.dp)
                )
            }
        }
    }
}

@Composable
inline fun FavoriteEmojis(width:Int, height:Int, backgroundColor: Color){
    Box(modifier = Modifier.width(width.dp).height(height.dp).background(backgroundColor)){
        LazyColumn {
            items (8) {

                Image(painter = painterResource(R.drawable.ic_eclipse),
                    contentDescription = "",
                    modifier = Modifier
                        .width(400.dp)
                        .height(50.dp)
                        .padding(2.dp)
                )
            }
        }
    }
}